const Conversation = require('../../models/conversation')
const Message = require('../../models/message')

const sendMessage = (io) => async (req, res) => {
  try {
    const {message} = req.body
    const {id: recipientId} = req.params
    const {id: senderId} = req.user

    let conversation = await Conversation.findOne({
      participants: {$all: [senderId, recipientId]},
    })

    if (!conversation) {
      conversation = await Conversation.create({
        participants: [senderId, recipientId],
      })
    }

    const newMessage = new Message({
      senderId,
      recipientId,
      message,
    })

    if (newMessage) {
      conversation.messages.push(newMessage.id)
    }

    await Promise.all([conversation.save(), newMessage.save()])

    io.to(recipientId).emit('newMessage', newMessage)

    res.status(201).json(newMessage)
  } catch (err) {
    res.status(500).json({error: 'Internal Server Error'})
    console.error('Error: ' + err.message)
  }
}

const getMessages = async (req, res) => {
  try {
    const {id: userChatId} = req.params
    const {id: senderId} = req.user

    const conversation = await Conversation.findOne({
      participants: {$all: [senderId, userChatId]},
    }).populate('messages')

    if (!conversation) return res.status(200).json([])

    res.status(200).json(conversation.messages)
  } catch (err) {
    res.status(500).json({error: 'Internal Server Error'})
    console.error('Error: ' + err.message)
  }
}

module.exports = {sendMessage, getMessages}
